//
//  EditSeatsViewController.m
//  BaseProject
//
//  Created by 王洋 on 2020/11/13.
//  Copyright © 2020 王洋. All rights reserved.
//
#import "LSTPopView.h"

#import "EditSeatsCell.h"
#import "CommonSeatsModel.h"
#import "AddSeatUserView.h"

#import "EditSeatsSectionHeader.h"

#import "EditSeatsViewController.h"

@interface EditSeatsViewController ()<UITableViewDelegate, UITableViewDataSource, RTNavigationItemCustomizable>
@property (nonatomic, strong) UITableView *tableview;

@property (nonatomic, strong) UIButton *addBtn;
@property (nonatomic, strong) UIButton *delBtn;

@property (nonatomic, strong) AddSeatUserView *addView;
@property (nonatomic, strong) LSTPopView *popView;

@property (nonatomic, assign) BOOL isChanged;
@end

@implementation EditSeatsViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self initView];
}

- (void)initView {
    
    UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [rightBtn setTitleColor:UIColorHex(0x666666) forState:UIControlStateNormal];
    [rightBtn setTitle:@"保存" forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(saveAction) forControlEvents:UIControlEventTouchUpInside];
    rightBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    rightBtn.frame = CGRectMake(0,0,66,30);
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
    self.navigationItem.rightBarButtonItems =@[rightItem];
    
    [self.view addSubview:self.addBtn];
    [self.view addSubview:self.delBtn];

    [self.view addSubview:self.tableview];
    
    [self.addBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(0);
        make.height.mas_equalTo(50);
        make.width.mas_equalTo(TTScreenWidth/2);
        make.bottom.mas_equalTo(-Bottom_SafeHeight);
    }];
    
    [self.delBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.width.mas_equalTo(TTScreenWidth/2);
        make.height.mas_equalTo(50);
        make.bottom.mas_equalTo(-Bottom_SafeHeight);
    }];
    
    [self.tableview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.mas_equalTo(0);
        make.bottom.mas_equalTo(self.addBtn.mas_top);
    }];
    
    self.isChanged = NO;
    [self.tableview reloadData];
    
    [self initViewAction];
    self.rt_navigationController.delegate = self;

}

- (UIBarButtonItem *)rt_customBackItemWithTarget:(id)target action:(SEL)action {
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setImage:[UIImage imageNamed:@"public_back_black"] forState:UIControlStateNormal];
    btn.frame = CGRectMake(0, 0, 50, 44);
    btn.imageEdgeInsets = UIEdgeInsetsMake(0, -30, 0, 0);
    [btn addTarget:target action:@selector(goNaviBack) forControlEvents:UIControlEventTouchUpInside];
    return [[UIBarButtonItem alloc] initWithCustomView:btn];
}

- (void)goNaviBack {
    
    [self request_updateSeats];
    
}

- (void)initViewAction {
    
    WEAKSELF
    self.addView.AddSeatUserViewBlock = ^(NSString * _Nonnull name) {
        
        if (name.length > 0) {
            
            if ([name containsString:@" "]) {
                
                NSArray *array = [name componentsSeparatedByString:@" "];
                for (int i = 0; i < array.count; i++) {
                    
                    NSString *arrayStr = array[i];
                    if (arrayStr.length > 0) {
                        CommonUserSeatsModel *model = [[CommonUserSeatsModel alloc] init];
                        model.name = arrayStr;
                        model.carryNumber = @"1";
                        [weakSelf.model.userSeatList addObject:model];
                    }

                }
                
            } else {
                CommonUserSeatsModel *model = [[CommonUserSeatsModel alloc] init];
                model.name = name;
                model.carryNumber = @"1";
                [weakSelf.model.userSeatList addObject:model];
            }

            weakSelf.addView.nameTF.text = @"";
            [weakSelf.popView dismiss];
            [weakSelf.tableview reloadData];
        }
    };
}

- (void)calculateCount {
    
    NSInteger total = 0;
    for (int i = 0; i < self.model.userSeatList.count; i++) {
        
        NSInteger count = self.model.userSeatList[i].carryNumber.integerValue;
        total = total + count;
    }
    self.model.number = [NSString stringWithFormat:@"%ld",total];
}

- (void)handleAction {
    
    self.addView.frame = CGRectMake(0, 0, 278,200);
    self.popView = [LSTPopView initWithCustomView:self.addView
                                                popStyle:LSTPopStyleSpringFromTop
                                            dismissStyle:LSTDismissStyleSmoothToBottom];
    self.popView.hemStyle = LSTHemStyleCenter;
    
    WEAKSELF
    self.popView.popDuration = 0.5;
    self.popView.dismissDuration = 0.5;
    self.popView.isClickFeedback = YES;
    self.popView.bgClickBlock = ^{

        [weakSelf.popView dismiss];
    };

    [self.popView pop];
}

- (void)saveAction {
    
    [self.view endEditing:YES];
    
    [self request_updateSeats];
}

- (void)delAction {
    
    if ([self.model.isMainTable isEqualToString:@"1"]) {
        
        [SVProgressHUD showErrorWithStatus:@"主桌不可删除"];
        [SVProgressHUD dismissWithDelay:1];
        
    } else {
        
        [TT_Alert alert:@"是否确认删除本桌" cancleBtnTitle:@"拒绝" cancleAction:^{
                
            } doneBtnTitle:@"删除本桌" doneAction:^{
                [self request_deleteSeats];
            }];
    }
    

}

#pragma mark UITableviewDelegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.model.userSeatList.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 50;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 155;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    EditSeatsSectionHeader *headView = [[NSBundle mainBundle] loadNibNamed:@"EditSeatsSectionHeader"owner:nil options:nil].firstObject;
//    headView.seatNameTF.text = self.model.seatsName;
    headView.seatCountTF.text = self.model.seatsNumber;
    headView.seatUserCountLab.text = [NSString stringWithFormat:@"%@/%@已安排",self.model.number,self.model.seatsNumber];
        
    [RACObserve(headView.seatNameTF, text) subscribeNext:^(id x) {
        self.isChanged = YES;
        self.model.seatsName = headView.seatNameTF.text;
    }];
    
    [RACObserve(headView.seatCountTF, text) subscribeNext:^(id x) {
        self.isChanged = YES;
        self.model.seatsNumber = headView.seatCountTF.text;
        headView.seatUserCountLab.text = [NSString stringWithFormat:@"%@/%@已安排",self.model.number,self.model.seatsNumber];
    }];
    
    [RACObserve(self.model, number) subscribeNext:^(id x) {
        self.isChanged = YES;
        headView.seatUserCountLab.text = [NSString stringWithFormat:@"%@/%@已安排",self.model.number,self.model.seatsNumber];
    }];
    
    return  headView;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    EditSeatsCell *cell = [tableView dequeueReusableCellWithIdentifier:@"EditSeatsCellID"];
    cell.selectionStyle =UITableViewCellSelectionStyleNone;
//    [cell fillCellWithModel:self.dataArray[indexPath.section].goodsList[indexPath.row]];
    
    cell.itemTitleLab.text = self.model.userSeatList[indexPath.row].name;
    cell.itemCountTF.text = self.model.userSeatList[indexPath.row].carryNumber;
    
    WEAKSELF
    cell.EditSeatsCellBlock = ^(EditSeatsCellActionType type) {
      
        switch (type) {
            case EditSeatsCellActionType_del:{
                
                weakSelf.isChanged = YES;
                [weakSelf.model.userSeatList removeObjectAtIndex:indexPath.row];
                [weakSelf.tableview reloadData];
                
            } break;
                
            default:
                break;
        }
    };
    
    [RACObserve(cell.itemTitleLab, text) subscribeNext:^(id x) {
        
        self.isChanged = YES;
        if (self.model.userSeatList.count > indexPath.row) {
            self.model.userSeatList[indexPath.row].name = cell.itemTitleLab.text;
        }
    }];
    
    [RACObserve(cell.itemCountTF, text) subscribeNext:^(id x) {
        self.isChanged = YES;
        if (self.model.userSeatList.count > indexPath.row) {
            
            NSInteger count = cell.itemCountTF.text.integerValue;
            if (count >= 0) {
                self.model.userSeatList[indexPath.row].carryNumber = cell.itemCountTF.text;
            }
        }

        [self calculateCount];
    }];
    
    return cell;
}

- (UITableView *)tableview {
    if (!_tableview) {
        _tableview = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableview.delegate = self;
        _tableview.dataSource = self;
        _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableview.backgroundColor =  UIColorHex(0xf1f1f1);
        
        _tableview.showsHorizontalScrollIndicator = NO;
        _tableview.showsVerticalScrollIndicator = NO;
        
        _tableview.estimatedSectionHeaderHeight = 0;
        _tableview.estimatedSectionFooterHeight = 0;
        _tableview.estimatedRowHeight = 0;
        
        [_tableview registerNib:[UINib nibWithNibName:@"EditSeatsCell" bundle:nil] forCellReuseIdentifier:@"EditSeatsCellID"];
    }
    return _tableview;
}

- (UIButton *)addBtn {
    if (!_addBtn) {
        _addBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_addBtn setTitle:@"新增宾客" forState:UIControlStateNormal];
        _addBtn.titleLabel.font = [UIFont systemFontOfSize:14];
        [_addBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_addBtn addTarget:self action:@selector(handleAction) forControlEvents:UIControlEventTouchUpInside];
        [_addBtn setBackgroundColor:UIColorHex(0xFA534C)];

    }
    return _addBtn;
}

- (UIButton *)delBtn {
    if (!_delBtn) {
        _delBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _delBtn.titleLabel.font = [UIFont systemFontOfSize:14];
        [_delBtn setTitle:@"删除本桌" forState:UIControlStateNormal];
        [_delBtn setTitleColor:UIColorHex(0x333333) forState:UIControlStateNormal];
        [_delBtn setBackgroundColor:UIColorHex(0xffffff)];
        [_delBtn addTarget:self action:@selector(delAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _delBtn;
}

- (AddSeatUserView *)addView {
    if (!_addView) {
        _addView = [[NSBundle mainBundle] loadNibNamed:@"AddSeatUserView"owner:nil options:nil].firstObject;
    }
    return _addView;
}

- (void)request_updateSeats {
    
//    API_UpdateSeats
    NSMutableDictionary *dic = @{}.mutableCopy;

    dic = [self.model mj_JSONObject];
    NSMutableArray *userSeatList = @[].mutableCopy;
    for (int i = 0; i < self.model.userSeatList.count; i++) {
        NSDictionary *seatDic = [self.model.userSeatList[i] mj_JSONObject];
        [userSeatList addObject:seatDic];
    }
    [dic setValue:userSeatList forKey:@"userSeatList"];
    
    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,API_UpdateSeats];

    [SVProgressHUD showWithStatus:@"正在加载"];
    WEAKSELF
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {

    [SVProgressHUD dismiss];
    if ([data isKindOfClass:[NSDictionary class]]) {

        //请求成功
        NSInteger code = [[data valueForKey:@"code"] integerValue];
        if (code == 10000) {

            [weakSelf.navigationController popViewControllerAnimated:YES];
            [SVProgressHUD showSuccessWithStatus:@"保存成功"];
            [SVProgressHUD dismissWithDelay:1];
        }
    }

    } FailedBlock:^(NSError * _Nonnull error) {

    [SVProgressHUD dismiss];
    }];
    
}

- (void)request_deleteSeats {
    
    NSMutableDictionary *dic = @{}.mutableCopy;

    [dic setValue:@"1" forKey:@"isDel"];
    [dic setValue:self.model.wsId forKey:@"wsId"];

    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,API_DeleteSeats];

    [SVProgressHUD showWithStatus:@"正在加载"];
    WEAKSELF
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {

    [SVProgressHUD dismiss];
    if ([data isKindOfClass:[NSDictionary class]]) {

        //请求成功
        NSInteger code = [[data valueForKey:@"code"] integerValue];
        if (code == 10000) {

            [SVProgressHUD showSuccessWithStatus:@"删除成功"];
            [SVProgressHUD dismissWithDelay:1];
            [weakSelf.navigationController popViewControllerAnimated:YES];
        }
    }

    } FailedBlock:^(NSError * _Nonnull error) {

    [SVProgressHUD dismiss];
    }];
    
}

@end
